package com.quanyan.search.service.impl;

import com.alibaba.dubbo.common.json.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.common.constants.SearchConstants;
import com.quanyan.common.utils.PinYinUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.search.entity.request.ReqClubSearchInfo;
import com.quanyan.search.entity.response.ClubSearchResponse;
import com.quanyan.search.entity.response.SearchResponses;
import com.quanyan.search.entity.vo.ClubIndexInfo;
import com.quanyan.search.service.ClubSearchService;
import com.quanyan.search.utils.CommonUtil;
import com.quanyan.search.utils.SolrServerSingle;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.MapSolrParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * ClubSearchServiceImpl
 *
 * @author Tu Chun
 * @date 2016/6/27
 */
@Service
public class ClubSearchServiceImpl implements ClubSearchService {
    private static Logger logger = LoggerFactory.getLogger(ClubSearchServiceImpl.class);
    //public final static String URL = "192.168.30.75:2181,192.168.30.75:2182,192.168.30.75:2183";
    private String URL;

    public String getURL() {
        return URL;
    }

    public void setURL(String URL) {
        this.URL = URL;
    }

    public ClubSearchServiceImpl(String URL) {
        this.URL = URL;
    }

    public ClubSearchServiceImpl() {
    }


    /**
     * 添加俱乐部索引
     *
     * @param clubIndexInfo
     * @return
     */
    @Override
    public APIResponse insertDoc(ClubIndexInfo clubIndexInfo) {
        try {
            if (addDocUtil(clubIndexInfo)) {
                return APIResponse.returnSuccess("添加俱乐部" + clubIndexInfo.getClub_name() + "索引c成功");
            } else {
                return APIResponse.returnFail("添加俱乐部");
            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加俱乐部", e);
            return APIResponse.returnFail("添加俱乐部");
        }
    }

    /**
     * 添加多个场馆索引
     *
     * @param clubIndexInfos
     * @return
     */
    @Override
    public APIResponse insertDocs(List<ClubIndexInfo> clubIndexInfos) {
        try {
            Long startTime = System.currentTimeMillis();
            Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            for (int i = 0; i < clubIndexInfos.size(); i++) {
                ClubIndexInfo indexInfo = clubIndexInfos.get(i);
                //创建文档对象
                SolrInputDocument document = new SolrInputDocument();
                String uniqueId = SearchConstants.CLUB_ID_PREFIX + UUID.randomUUID().toString();
                document.addField("id", uniqueId);
                document.addField("club_id", indexInfo.getClub_id());
                document.addField("club_name_ik", indexInfo.getClub_name());
                document.addField("club_name", indexInfo.getClub_name());
                document.addField("club_name2", indexInfo.getClub_name());
                document.addField("club_logo", indexInfo.getClub_logo());
                document.addField("club_level", indexInfo.getClub_level());
                document.addField("club_star", indexInfo.getClub_star());
                document.addField("club_founder_uid", indexInfo.getClub_founder_uid());
                document.addField("club_founder_nickname", indexInfo.getClub_founder_nickname());
                document.addField("club_sport_name", indexInfo.getClub_sport_name());
                document.addField("club_city_id", indexInfo.getClub_city_id());
                document.addField("club_city_name", indexInfo.getClub_city_name());
                document.addField("club_district_id", indexInfo.getClub_district_id());
                document.addField("club_district_name", indexInfo.getClub_district_name());
                document.addField("club_integral", indexInfo.getClub_integral());
                document.addField("club_type_id", indexInfo.getClub_type_id());
                document.addField("resident_place_id", indexInfo.getResident_place_id());
                document.addField("club_latlng", indexInfo.getClub_lat() + "," + indexInfo.getClub_lng());
                if (indexInfo.getClub_activity_count() == null) {
                    document.addField("club_activity_count", -1);
                } else {
                    document.addField("club_activity_count", indexInfo.getClub_activity_count());
                }

                document.addField("club_name_pinyin", indexInfo.getClub_name_pinyin());
                document.addField("club_name_first_letter", indexInfo.getClub_name_first_letter());
                document.addField("club_founder_nickname_pinyin", indexInfo.getClub_founder_nickname_pinyin());
                document.addField("club_founder_nickname_first_letter", indexInfo.getClub_founder_nickname_first_letter());
                List<Integer> members = indexInfo.getClub_member_uids();
                if (!CommonUtil.isNullOrZero(members)) {
                    for (int j = 0; j < members.size(); j++) {
                        document.addField("club_member_uids", members.get(j));
                    }
                }
                List<String> membersName = indexInfo.getClub_member_nicknames();
                if (!CommonUtil.isNullOrZero(membersName)) {
                    for (int j = 0; j < members.size(); j++) {
                        document.addField("club_member_nicknames", members.get(j));
                    }
                }
                solrServer.add(document);
                docs.add(document);
                logger.info("添加" + i + "号索引到文档中");
            }
            solrServer.add(docs);
            solrServer.commit();
            Long endTime = System.currentTimeMillis();
            logger.info("添加索引" + clubIndexInfos.size() + "条执行时间：" + ((endTime - startTime) / (60 * 1000)) + "分钟.");
            return APIResponse.returnSuccess("添加多个俱乐部索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加多个俱乐部索引异常", e);
            return APIResponse.returnFail("添加多个俱乐部索引失败");
        }
    }

    /**
     * 根据id删除Document
     *
     * @param club_id club_member_uid
     * @return
     */
    @Override
    public APIResponse deleteDocById(Integer club_id) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            StringBuilder stringBuilder = new StringBuilder();
            if (CommonUtil.isNullOrZero(club_id)) {
                return APIResponse.returnFail("俱乐部id不能为空");
            } else if (!CommonUtil.isNullOrZero(club_id)) {
                stringBuilder.append("club_id:").append(club_id);
            }
            solrServer.deleteByQuery(stringBuilder.toString());
            solrServer.commit();
            return APIResponse.returnSuccess("删除俱乐部索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "删除俱乐部索引异常", e);
            return APIResponse.returnFail("删除俱乐部引失败");
        }
    }


    /**
     * 删除多个Document
     *
     * @param ids
     * @return
     */
    @Override
    public APIResponse deleteDocsByIds(List<Integer> ids) {

        try {
            if (CommonUtil.isNullOrZero(ids)) {
                return APIResponse.returnFail("俱乐部ids不能为空");
            }
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            solrServer.setDefaultCollection("collection2");

            StringBuilder stringBuilder = new StringBuilder();
//            stringBuilder.append("club_id:(");
//            for (int i = 0; i < ids.size(); i++) {
//                Integer id = ids.get(i);
//                if (i == 0) {
//                    stringBuilder.append(id);
//                } else {
//                    stringBuilder.append(" OR ").append(id);
//                }
//            }
//            stringBuilder.append(")");
            stringBuilder.append("club_id:*");
            logger.warn("批量删除条件：" + stringBuilder.toString());
            solrServer.deleteByQuery(stringBuilder.toString());
            solrServer.commit();


            return APIResponse.returnSuccess("删除多个俱乐部索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "删除多个俱乐部索引异常", e);
            return APIResponse.returnFail("删除多个俱乐部引失败");
        }

    }

    /**
     * 根据id搜索俱乐部信息
     *
     * @param club_id
     * @return
     */
    @Override
    public APIResponse<ClubIndexInfo> searchClubInfo(Integer club_id) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            StringBuilder stringBuilder = new StringBuilder();
            if (CommonUtil.isNullOrZero(club_id)) {
                return APIResponse.returnFail("俱乐部id不能为空");
            } else if (!CommonUtil.isNullOrZero(club_id)) {
                stringBuilder.append("club_id:").append(club_id);

            }

            params.put("q", stringBuilder.toString());
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            List<ClubIndexInfo> clubIndexInfos = response.getBeans(ClubIndexInfo.class);
            //List<PlaceSearchResponse> responses=getPlaceSearchResponseList(placeIndexInfoList,null,null);
            return APIResponse.returnSuccess(CommonUtil.isNullOrZero(clubIndexInfos) ? null : clubIndexInfos.get(0));
        } catch (Exception e) {
            logger.error(e.getMessage() + "根据id搜索俱乐部异常", e);
            return APIResponse.returnFail("根据id搜索俱乐部失败");
        }
    }

    /**
     * 根据条件搜索 新方法
     *
     * @param reqClubSearchInfo
     * @return
     */
    public APIResponse<SearchResponses<List<ClubSearchResponse>>> searchClubInfoListNew(ReqClubSearchInfo reqClubSearchInfo) {

        try {
            SearchResponses<List<ClubSearchResponse>> searchResponses = new SearchResponses<List<ClubSearchResponse>>();
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            //俱乐部id
            Integer club_id = reqClubSearchInfo.getClub_id();
            //俱乐部名字
            String club_name = reqClubSearchInfo.getClub_name();
            //俱乐部创始人用户id
            Integer club_founder_uid = reqClubSearchInfo.getClub_founder_uid();
            //俱乐部创始人昵称		(需根据昵称拼音首字母搜索)
            String club_founder_nickname = reqClubSearchInfo.getClub_founder_nickname();
            //俱乐部运动类型
            String club_sport_name = reqClubSearchInfo.getClub_sport_name();
            //城市id
            Integer city_id = reqClubSearchInfo.getCity_id();
            //区域id
            Integer district_id = reqClubSearchInfo.getDistrict_id();
            Byte type = reqClubSearchInfo.getType();

            Integer club_type_id = reqClubSearchInfo.getClub_type_id();
            //俱乐部场馆id
            Integer resident_place_id = reqClubSearchInfo.getResident_place_id();
            Double lat = reqClubSearchInfo.getLat();
            Double lng = reqClubSearchInfo.getLng();
            //俱乐部正在报名中的活动数
            Integer signup_activity_count = reqClubSearchInfo.getSignup_activity_count();
            //搜索距离
            Double distance = reqClubSearchInfo.getDistance();
            //排序条件：俱乐部报名人数、星级、距离
            Map<String, String> sortMap = reqClubSearchInfo.getSortMap();
            String clubSignupCountVal = null;
            String starSortVal = null;
            String clubDistVal = null;

            if (sortMap != null && !sortMap.isEmpty()) {
                clubSignupCountVal = sortMap.get("club_activity_count");
                starSortVal = sortMap.get("club_star");
                clubDistVal = sortMap.get("club_dist");
            }


            Integer pageNo = reqClubSearchInfo.getPageNo();
            Integer pageSize = reqClubSearchInfo.getPageSize();
            Integer startPosition = pageNo * pageSize;
            StringBuilder builder = new StringBuilder();

            if (StringUtil.isBlankOrNull(club_sport_name)) {
                club_sport_name = "*";
            }
            builder.append("club_sport_name:").append(club_sport_name);
            if (!StringUtil.isBlankOrNull(club_name)) {
                if (type == 1) {
                    //汉字优先搜索
                  /*  club_name:好的^600.0 OR club_name:*haode*
                            OR club_name_first_letter:h^0.0001 OR club_name:*hao**/
                    String clubNamePingyin = PinYinUtils.hanyuToPinyin(club_name);
                    if(clubNamePingyin != null) {
                        clubNamePingyin = clubNamePingyin.replaceAll(":", "");
                    }
                    String clubNameFirstPingyin = PinYinUtils.hanyuToPinyin(club_name.charAt(0) + "");
                    if (clubNameFirstPingyin != null) {
                        clubNameFirstPingyin = clubNameFirstPingyin.replaceAll(":", "");
                    }
                    builder.append(" AND (club_name_ik:").append(club_name + "^100");
                    builder.append(" OR club_name_pinyin:").append(clubNamePingyin + "*^600");
                    builder.append(" OR club_name_ik:").append(club_name + "*");
                    builder.append(")");

                } else if (type == 2) {
                    //英文优先搜索
                    /*club_name:*zaoshui*^600
                    OR club_name_pinyin:*zaoshui*^600
                     OR club_name2:*zaoshui*^600
                      OR club_name_first_letter:z*/
                    builder.append(" AND (club_name:").append(club_name + "^600");
                    builder.append(" OR club_name_pinyin:").append("*" + club_name + "*" + "^600");
                    builder.append(" OR club_name2:").append("*" + club_name + "*" + "^600");
                    builder.append(" OR club_name_first_letter:").append(club_name.charAt(0) + "");
                    builder.append(")");
                } else if (type == 3) {
                    //首字母优先搜索
                    /*club_name:h*^600
                    OR club_name_first_letter:h
                    OR club_name2:h**/
                    builder.append(" AND (club_name:").append(club_name + "*" + "^600");
                    builder.append(" OR club_name_first_letter:").append(club_name);
                    builder.append(" OR club_name2:").append(club_name + "*" + "^600");
                    builder.append(")");
                } else if (type == 4) {
                    //英文汉字混合
                    builder.append(" AND (club_name2:").append("*" + club_name + "*" + "^600");
                    builder.append(" OR club_name_ik:").append(club_name + "*^600");
                    builder.append(" OR club_name2:").append(club_name);
                    builder.append(")");
                }

            }

            if (!CommonUtil.isNullOrZero(city_id)) {
                builder.append(" AND club_city_id:").append(city_id);
            }

            if (!CommonUtil.isNullOrZero(district_id)) {
                builder.append(" AND club_district_id:").append(district_id);
            }

            if (!CommonUtil.isNullOrZero(club_type_id)) {
                builder.append(" AND club_type_id:").append(club_type_id);
            }
            if (!CommonUtil.isNullOrZero(resident_place_id)) {
                builder.append(" AND resident_place_id:").append(resident_place_id);
            }
            if (!StringUtil.isBlankOrNull(clubDistVal)) {
                builder.append(" AND club_type_id:").append("[0 TO 4]");
            }
            logger.warn("query:" + builder.toString());
            params.put("q", builder.toString());

            params.put("fq", "{!geofilt}");//距离过滤函数

            params.put("pt", CommonUtil.getLatLng(lat, lng));//当前经纬度


            params.put("sfield", "club_latlng");//经纬度的字段
            params.put("d", distance.toString());

            if ("asc".equals(clubSignupCountVal)) {
                //params.put("sort", "club_activity_count asc, score desc");//根据报名人数排序
                params.put("sort", "club_activity_count asc,club_star desc,club_id asc, score desc");//综合排序*//
            } else if ("desc".equals(clubSignupCountVal)) {
                //params.put("sort", "club_activity_count desc, score desc");//根据报名人数排序
                params.put("sort", "club_activity_count desc,club_star desc,club_id asc, score desc");//综合排序*//
            } else if ("asc".equals(starSortVal)) {
                params.put("sort", "club_star asc,club_activity_count desc,club_id asc, score desc");//根据星级升序排序
            } else if ("desc".equals(starSortVal)) {
                params.put("sort", "club_star desc ,club_activity_count desc,club_id asc, score desc");//根据星级降序排序
            } else if ("asc".equals(clubDistVal)) {
                params.put("sort", "geodist() asc,club_star desc,club_id asc, score desc");//根据距离升序排序
            } else if ("desc".equals(clubDistVal)) {
                params.put("sort", "geodist() desc,club_star desc,club_id asc, score desc");//根据等级降序排序
            }
//            else {
//                params.put("sort", "club_activity_count desc,club_star desc,club_id asc, score desc");//默认综合排序*//
//            }
            /*else {
               *//* params.put("defType", "edismax");
                params.put("bf", "div(10,geodist())");
                params.put("sort", "score desc,geodist() asc");//默认综合排序*//*
            }*/

            params.put("fl", "*,club_dist:geodist(),score");
            params.put("start", startPosition.toString());//记录开始位置
            params.put("rows", pageSize.toString());//查询的行数
            params.put("df", "club_keywords");   // 设置默认搜索域
            //不传关键字为0 传关键字为1
            int flag = 0;
            //设置高亮
            /*if (!StringUtil.isBlankOrNull(club_name)) {
                params.put("hl", "true");
                params.put("hl.fl", "club_name");
                params.put("hl.simple.pre", "<em style=\"color:red\">");
                params.put("hl.simple.post", "</em>");
               flag=1;
            }*/
            params.put("shards.tolerant", "true");
            logger.warn("params:" + JSON.json(params));
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            long total = solrDocumentList.getNumFound();
            //取高亮显示
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            //List<PlaceIndexInfo> placeIndexInfoList = response.getBeans(PlaceIndexInfo.class);
            List<ClubSearchResponse> clubResList = getClubSearchResponseListNew(solrDocumentList, highlighting, flag);
            searchResponses.setData(clubResList);
            searchResponses.setPageNo(pageNo);
            searchResponses.setPageSize(pageSize);
            searchResponses.setTotal((int) total);

            return APIResponse.returnSuccess(searchResponses);
        } catch (Exception e) {
            logger.error(e.getMessage() + "搜索数据异常", e);
            return APIResponse.returnFail("搜索数据异常");


        }

    }

    private List<ClubSearchResponse> getClubSearchResponseListNew(SolrDocumentList solrDocumentList, Map<String, Map<String, List<String>>> highlighting, int flag) throws ParseException, IOException {
        List<ClubSearchResponse> clubSearchResponses = new ArrayList<ClubSearchResponse>();
        List<ClubIndexInfo> clubIndexInfos = new ArrayList<ClubIndexInfo>();

        for (SolrDocument solrDocument : solrDocumentList) {
            ClubIndexInfo indexInfo = new ClubIndexInfo();
            //解析solr中数据
            String id = (String) solrDocument.get("id");
            String club_id = (String) solrDocument.get("club_id");
            String club_name = (String) solrDocument.get("club_name");
            String club_logo = (String) solrDocument.get("club_logo");
            Integer club_level = (Integer) solrDocument.get("club_level");
            Double club_star = (Double) solrDocument.get("club_star");
            Integer club_founder_uid = (Integer) solrDocument.get("club_founder_uid");
            String club_founder_nickname = (String) solrDocument.get("club_founder_nickname");
            String club_sport_name = (String) solrDocument.get("club_sport_name");
            Integer city_id = (Integer) solrDocument.get("club_city_id");
            String city_name = (String) solrDocument.get("club_city_name");
            Integer district_id = (Integer) solrDocument.get("club_district_id");
            Integer club_type_id = (Integer) solrDocument.get("club_type_id");
            String district_name = (String) solrDocument.get("club_district_name");

            Double club_integral = (Double) solrDocument.get("club_integral");
            List<Integer> club_member_uids = (List<Integer>) solrDocument.get("club_member_uids");
            List<String> club_member_nicknames = (List<String>) solrDocument.get("club_member_nicknames");
            club_name = (String) solrDocument.get("club_name");
            Float club_dist = (Float) solrDocument.get("club_dist");
            //转换成米
            if (club_dist != null) {
                club_dist=club_dist*1000;
            }
            Integer club_activity_count = (Integer) solrDocument.get("club_activity_count");

            //取高亮显示的结果
            if (flag == 1) {
                List<String> list = highlighting.get(solrDocument.get("id")).get("club_name");
                if (list != null && list.size() > 0) {
                    club_name = list.get(0);
                } else {
                    club_name = (String) solrDocument.get("club_name");
                }
            }


            List<Date> startDateList = new ArrayList<Date>();


            //测试打印数据
            indexInfo.setId(id);
            indexInfo.setClub_id(club_id);
            indexInfo.setClub_name(club_name);
            indexInfo.setClub_logo(club_logo);
            indexInfo.setClub_level(club_level);
            indexInfo.setClub_star(club_star);
            indexInfo.setClub_founder_uid(club_founder_uid);
            indexInfo.setClub_founder_nickname(club_founder_nickname);
            indexInfo.setClub_sport_name(club_sport_name);
            indexInfo.setClub_city_id(city_id);
            indexInfo.setClub_city_name(city_name);
            indexInfo.setClub_district_id(district_id);
            indexInfo.setClub_district_name(district_name);
            indexInfo.setClub_integral(club_integral);
            indexInfo.setClub_type_id(club_type_id);
            indexInfo.setClub_member_uids(club_member_uids);
            indexInfo.setClub_member_nicknames(club_member_nicknames);
            indexInfo.setClub_dist(club_dist.doubleValue());
            indexInfo.setClub_activity_count(club_activity_count);
            clubIndexInfos.add(indexInfo);


            //封装返回的数据
            ClubSearchResponse clubRes = new ClubSearchResponse();
            clubRes.setClub_id(!StringUtil.isBlankOrNull(club_id) ? Integer.parseInt(club_id) : 0);
            clubRes.setClub_logo(club_logo);
            clubRes.setClub_level(club_level);
            clubRes.setClub_star(club_star);
            clubRes.setClub_integral(club_integral);
            clubRes.setClub_name(club_name);
            clubRes.setClub_founder_uid(club_founder_uid);
            clubRes.setClub_founder_nickname(club_founder_nickname);
            clubRes.setClub_sport_name(club_sport_name);
            clubRes.setCity_name(city_name);
            clubRes.setDistrict(district_name);
            clubRes.setClub_type_id(club_type_id);
            clubRes.setClub_dist(club_dist.doubleValue());
            clubRes.setClub_activity_count(club_activity_count);
            //不可预订的场馆不显示
            /*if (!StringUtil.isBlankOrNull(date) && !CommonUtil.isNullOrZero(startTimeList)){
                for(int j=0;j<startTimeList.size();j++){
                    for(int k=0;k<startDateList.size();k++){

                    }
                }
                continue;
            }*/

            clubSearchResponses.add(clubRes);
        }
        //测试打印数据
        logger.warn("clubIndexInfo-size:" + clubIndexInfos.size());
        logger.warn("clubIndexInfo:" + JSON.json(clubIndexInfos));

        return clubSearchResponses;

    }

    /**
     * 根据条件搜索
     *
     * @param reqClubSearchInfo
     * @return
     */
    @Override
    public APIResponse<SearchResponses<List<ClubSearchResponse>>> searchClubInfoList(ReqClubSearchInfo reqClubSearchInfo) {

        try {
            SearchResponses<List<ClubSearchResponse>> searchResponses = new SearchResponses<List<ClubSearchResponse>>();
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            //俱乐部id
            Integer club_id = reqClubSearchInfo.getClub_id();
            //俱乐部名字
            String club_name = reqClubSearchInfo.getClub_name();
            //俱乐部创始人用户id
            Integer club_founder_uid = reqClubSearchInfo.getClub_founder_uid();
            //俱乐部创始人昵称		(需根据昵称拼音首字母搜索)
            String club_founder_nickname = reqClubSearchInfo.getClub_founder_nickname();
            //俱乐部运动类型
            String club_sport_name = reqClubSearchInfo.getClub_sport_name();
            //城市id
            Integer city_id = reqClubSearchInfo.getCity_id();
            //区域id
            Integer district_id = reqClubSearchInfo.getDistrict_id();

            Integer club_type_id = reqClubSearchInfo.getClub_type_id();

            Integer resident_place_id = reqClubSearchInfo.getResident_place_id();
            //排序条件：俱乐部积分、星级、等级
            Map<String, String> sortMap = reqClubSearchInfo.getSortMap();
            String integralSortVal = null;
            String starSortVal = null;
            String levelSortVal = null;

            if (sortMap != null && !sortMap.isEmpty()) {
                integralSortVal = sortMap.get("club_integral");
                starSortVal = sortMap.get("club_star");
                levelSortVal = sortMap.get("club_level");
            }


            Integer pageNo = reqClubSearchInfo.getPageNo();
            Integer pageSize = reqClubSearchInfo.getPageSize();
            Integer startPosition = pageNo * pageSize;
            StringBuilder builder = new StringBuilder();

            if (StringUtil.isBlankOrNull(club_sport_name)) {
                club_sport_name = "*";
            }
            builder.append("club_sport_name:").append(club_sport_name);
            if (!StringUtil.isBlankOrNull(club_founder_nickname) && !StringUtil.isBlankOrNull(club_name)) {
                //俱乐部加权重
                builder.append(" AND (club_name:").append(club_name + "^1.9");
                builder.append(" OR club_founder_nickname:").append(club_founder_nickname);
                builder.append(")");
            }

            if (!CommonUtil.isNullOrZero(city_id)) {
                builder.append(" AND club_city_id:").append(city_id);
            }

            if (!CommonUtil.isNullOrZero(district_id)) {
                builder.append(" AND club_district_id:").append(district_id);
            }

            if (!CommonUtil.isNullOrZero(club_type_id)) {
                builder.append(" AND club_type_id:").append(club_type_id);
            }
            if (!CommonUtil.isNullOrZero(resident_place_id)) {
                builder.append(" AND resident_place_id:").append(resident_place_id);
            }
            logger.warn("query:" + builder.toString());
            params.put("q", builder.toString());

            if ("asc".equals(integralSortVal)) {
                params.put("sort", "club_integral asc, score desc");//根据积分升序排序
            } else if ("desc".equals(integralSortVal)) {
                params.put("sort", "club_integral desc, score desc");//根据积分降序排序
            }
            if ("asc".equals(starSortVal)) {
                params.put("sort", "club_star asc, score desc");//根据星级升序排序
            } else if ("desc".equals(starSortVal)) {
                params.put("sort", "club_star desc, score desc");//根据星级降序排序
            }
            if ("asc".equals(levelSortVal)) {
                params.put("sort", "club_level asc, score desc");//根据等级升序排序
            } else if ("desc".equals(levelSortVal)) {
                params.put("sort", "club_level desc, score desc");//根据等级降序排序
            }

            params.put("fl", "*,score");
            params.put("start", startPosition.toString());//记录开始位置
            params.put("rows", pageSize.toString());//查询的行数
            params.put("df", "club_keywords");   // 设置默认搜索域

            //设置高亮
          /*  params.put("hl", "true");
            params.put("hl.fl", "club_name");
            params.put("hl.simple.pre", "<em style=\"color:red\">");
            params.put("hl.simple.post", "</em>");*/
            logger.warn("params:" + JSON.json(params));
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            long total = solrDocumentList.getNumFound();
            //取高亮显示
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            //List<PlaceIndexInfo> placeIndexInfoList = response.getBeans(PlaceIndexInfo.class);
            List<ClubSearchResponse> clubResList = getClubSearchResponseList(solrDocumentList, highlighting);
            searchResponses.setData(clubResList);
            searchResponses.setPageNo(pageNo);
            searchResponses.setPageSize(pageSize);
            searchResponses.setTotal((int) total);

            return APIResponse.returnSuccess(searchResponses);
        } catch (Exception e) {
            logger.error(e.getMessage() + "搜索数据异常", e);
            return APIResponse.returnFail("搜索数据异常");


        }

    }

    private List<ClubSearchResponse> getClubSearchResponseList(SolrDocumentList solrDocumentList, Map<String, Map<String, List<String>>> highlighting) throws ParseException, IOException {
        List<ClubSearchResponse> clubSearchResponses = new ArrayList<ClubSearchResponse>();
        List<ClubIndexInfo> clubIndexInfos = new ArrayList<ClubIndexInfo>();

        for (SolrDocument solrDocument : solrDocumentList) {
            ClubIndexInfo indexInfo = new ClubIndexInfo();
            //解析solr中数据
            String id = (String) solrDocument.get("id");
            String club_id = (String) solrDocument.get("club_id");
            String club_name = (String) solrDocument.get("club_name");
            String club_logo = (String) solrDocument.get("club_logo");
            Integer club_level = (Integer) solrDocument.get("club_level");
            Double club_star = (Double) solrDocument.get("club_star");
            Integer club_founder_uid = (Integer) solrDocument.get("club_founder_uid");
            String club_founder_nickname = (String) solrDocument.get("club_founder_nickname");
            String club_sport_name = (String) solrDocument.get("club_sport_name");
            Integer city_id = (Integer) solrDocument.get("club_city_id");
            String city_name = (String) solrDocument.get("club_city_name");
            Integer district_id = (Integer) solrDocument.get("club_district_id");
            Integer club_type_id = (Integer) solrDocument.get("club_type_id");
            String district_name = (String) solrDocument.get("club_district_name");

            Double club_integral = (Double) solrDocument.get("club_integral");
            List<Integer> club_member_uids = (List<Integer>) solrDocument.get("club_member_uids");
            List<String> club_member_nicknames = (List<String>) solrDocument.get("club_member_nicknames");
            club_name = (String) solrDocument.get("club_name");
            /*//取高亮显示的结果
            List<String> list = highlighting.get(solrDocument.get("id")).get("club_name");
            if (list != null && list.size() > 0) {
                club_name = list.get(0);
            } else {
                club_name = (String) solrDocument.get("club_name");
            }*/

            List<Date> startDateList = new ArrayList<Date>();


            //测试打印数据
            indexInfo.setId(id);
            indexInfo.setClub_id(club_id);
            indexInfo.setClub_name(club_name);
            indexInfo.setClub_logo(club_logo);
            indexInfo.setClub_level(club_level);
            indexInfo.setClub_star(club_star);
            indexInfo.setClub_founder_uid(club_founder_uid);
            indexInfo.setClub_founder_nickname(club_founder_nickname);
            indexInfo.setClub_sport_name(club_sport_name);
            indexInfo.setClub_city_id(city_id);
            indexInfo.setClub_city_name(city_name);
            indexInfo.setClub_district_id(district_id);
            indexInfo.setClub_district_name(district_name);
            indexInfo.setClub_integral(club_integral);
            indexInfo.setClub_type_id(club_type_id);
            indexInfo.setClub_member_uids(club_member_uids);
            indexInfo.setClub_member_nicknames(club_member_nicknames);
            clubIndexInfos.add(indexInfo);


            //封装返回的数据
            ClubSearchResponse clubRes = new ClubSearchResponse();
            clubRes.setClub_id(!StringUtil.isBlankOrNull(club_id) ? Integer.parseInt(club_id) : 0);
            clubRes.setClub_logo(club_logo);
            clubRes.setClub_level(club_level);
            clubRes.setClub_star(club_star);
            clubRes.setClub_integral(club_integral);
            clubRes.setClub_name(club_name);
            clubRes.setClub_founder_uid(club_founder_uid);
            clubRes.setClub_founder_nickname(club_founder_nickname);
            clubRes.setClub_sport_name(club_sport_name);
            clubRes.setCity_name(city_name);
            clubRes.setDistrict(district_name);
            clubRes.setClub_type_id(club_type_id);
            //不可预订的场馆不显示
            /*if (!StringUtil.isBlankOrNull(date) && !CommonUtil.isNullOrZero(startTimeList)){
                for(int j=0;j<startTimeList.size();j++){
                    for(int k=0;k<startDateList.size();k++){

                    }
                }
                continue;
            }*/

            clubSearchResponses.add(clubRes);
        }
        //测试打印数据
        logger.warn("clubIndexInfo-size:" + clubIndexInfos.size());
        logger.warn("clubIndexInfo:" + JSON.json(clubIndexInfos));

        return clubSearchResponses;

    }


    private boolean addDocUtil(ClubIndexInfo indexInfo) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            //创建文档对象
            SolrInputDocument document = new SolrInputDocument();
            String uniqueId = SearchConstants.CLUB_ID_PREFIX + UUID.randomUUID().toString();
            document.addField("id", uniqueId);
            document.addField("club_id", indexInfo.getClub_id());
            document.addField("club_name_ik", indexInfo.getClub_name());
            document.addField("club_name", indexInfo.getClub_name());
            document.addField("club_name2", indexInfo.getClub_name());
            document.addField("club_logo", indexInfo.getClub_logo());
            document.addField("club_level", indexInfo.getClub_level());
            document.addField("club_star", indexInfo.getClub_star());
            document.addField("club_founder_uid", indexInfo.getClub_founder_uid());
            document.addField("club_founder_nickname", indexInfo.getClub_founder_nickname());
            document.addField("club_sport_name", indexInfo.getClub_sport_name());
            document.addField("club_city_id", indexInfo.getClub_city_id());
            document.addField("club_city_name", indexInfo.getClub_city_name());
            document.addField("club_district_id", indexInfo.getClub_district_id());
            document.addField("club_district_name", indexInfo.getClub_district_name());
            document.addField("club_integral", indexInfo.getClub_integral());
            document.addField("club_type_id", indexInfo.getClub_type_id());
            document.addField("resident_place_id", indexInfo.getResident_place_id());
            document.addField("club_latlng", indexInfo.getClub_lat() + "," + indexInfo.getClub_lng());
            if (indexInfo.getClub_activity_count() == null) {
                document.addField("club_activity_count", 0);
            } else {
                document.addField("club_activity_count", indexInfo.getClub_activity_count());
            }
            document.addField("club_name_pinyin", indexInfo.getClub_name_pinyin());
            document.addField("club_name_first_letter", indexInfo.getClub_name_first_letter());
            document.addField("club_founder_nickname_pinyin", indexInfo.getClub_founder_nickname_pinyin());
            document.addField("club_founder_nickname_first_letter", indexInfo.getClub_founder_nickname_first_letter());
            List<Integer> members = indexInfo.getClub_member_uids();
            if (!CommonUtil.isNullOrZero(members)) {
                for (int i = 0; i < members.size(); i++) {
                    document.addField("club_member_uids", members.get(i));
                }
            }
            List<String> membersName = indexInfo.getClub_member_nicknames();
            if (!CommonUtil.isNullOrZero(membersName)) {
                for (int i = 0; i < members.size(); i++) {
                    document.addField("club_member_nicknames", members.get(i));
                }
            }
            //document.addField("club_member_nickname",indexInfo.getClub_member_nickname());


            solrServer.add(document);
            solrServer.commit();
            logger.info("添加俱乐部索引成功");
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加俱乐部索引失败", e);
            return false;
        }
    }
}
